<template>
  <base-breadcrumb class="" :breadcrumb="!isAudit">
    <!-- 总包结算定案审批 -->
    <a-spin :spinning="loading">
      <a-card :bordered="false">
        <title-name title="基本信息"></title-name>
        <custom-form ref="customForm" :isEmit="false" :form="form" :edit-model="'E'"
                     :form-list="formList" :rules="rules" is-validate @select="selectOrg" />
      </a-card>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div v-if="!isConsultation" class="btn_box page-btn-right-top">
      <a-button :disabled="loading" :loading="defloading" v-if="editable" type="primary"
                class="button_right" @click="save">保存草稿</a-button>

      <a-button :disabled="loading" :loading="subloading" v-if="editable" type="primary"
                class="button_right" @click="handleSubmit(1)">提交</a-button>
      <a-button @click="$close">关闭</a-button>
    </div>
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import UploadList from '@/components/UploadList'
import BaseInputNumber from '@/components/BaseInputNumber'
import BSelect from '@/components/BComponents/BSelect'
import { getFinalDetail, finalApprovalAdd, finalApprovalUpdate, getFilterSubmission } from '@/api/businessAffairs/finalApproval'
import MathTool from '@/tool/MathTool.js'

export default {
  name: 'a' + Date.now(),
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: {
        programForm: false
      },
      loading: false, // 加载控件
      defloading: false,
      subloading: false,
      form: {
        fileInfoList: [],
      }, // 表单
      rules: {
        submissionId: [{ required: true, message: '请选择名称', trigger: 'change' }],
        judgementSettlementTime: [{ required: true, message: '请选择审定结算书日期', trigger: 'change' }],
        authorizedAmountNo: [{ required: true, message: '请输入审定金额（不含税）', trigger: 'blur' }],
        authorizedAmountTaxes: [{ required: true, message: '请输入审定金额（税金）（元）', trigger: 'blur' }],
      }, // 校验规则
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },

  async mounted() {
    if (this.type == 'add') {
      console.log(MathTool)
    } else {
      this.getDetail()
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('contractor_settlement_verdict_audit_new');
  },
  computed: {
    type() {
      return this.$route.query.type
    },
    editable() {
      return this.type == 'add' || this.type == 'edit'
    },
    curTagCode() {
      return this.$currentPost().id
    },
    curEmployee() {
      return this.$userInfo().employee.levels
    },
    ownOrgList() {
      let levels = [...this.$userInfo().employee.levels]
      let ownOrg = levels.filter((v) => {
        return v.code === 'CO' || v.code === 'BC'
      })
      ownOrg.forEach((v) => {
        if (v.code == 'CO') v.name = '总部机关'
      })
      return ownOrg
    },
    curTableKey() {
      return 'localId'
      // return this.type == 'add' ? 'localId' : 'id'
    },
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: false,
          isNeedAuth: true,
          checkStrictly: true,
          disabled: true,
          viewName: "viewName",
        },
        {
          keyName: 'submissionId',
          type: BSelect,
          disabled: (!this.editable),
          label: '名称',
          attrs: {
            form: this.form,
            keyValue: 'projectId',
            request: this.getNameList
          },
          selectChange: (e) => {
            this.form.considerationSettlementTime = e.submitDate
            this.form.costContract = e.contractCost
            this.form.reportAfterValue = e.adjustedAmount
            this.form.actualCostHas = e.actCost
            this.form.name = e.name
          }
        },
        {
          keyName: 'considerationSettlementTime',
          type: 'a-input',
          disabled: true,
          placeholder: ' ',
          label: '送审结算书日期',
        },
        {
          keyName: 'judgementSettlementTime',
          type: 'a-date-picker',
          label: '审定结算书日期',
          disabled: (!this.editable),
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            format: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'costContract',
          type: 'a-input',
          disabled: true,
          label: '合同造价（元）',
          placeholder: ' ',
        },
        {
          keyName: 'reportAfterValue',
          type: 'a-input',
          disabled: true,
          label: '调整后报审值（含税）（元）',
          placeholder: ' ',
        },
        {
          keyName: 'authorizedAmountNo',
          type: BaseInputNumber,
          disabled: (!this.editable),
          label: '审定金额（不含税）（元）',
          precision: 2,
          attrs: {
            min: 0,
            max: Infinity
          },
          packageInput: this.computedNum
        },
        {
          keyName: 'authorizedAmountTaxes',
          type: BaseInputNumber,
          disabled: (!this.editable),
          label: '审定金额（税金）（元）',
          precision: 2,
          attrs: {
            min: 0,
            max: Infinity
          },
          packageInput: this.computedNum
        },
        {
          keyName: 'authorizedAmountHas',
          type: 'a-input',
          disabled: true,
          placeholder: ' ',
          label: '审定金额（含税）（元）',
        },
        {
          keyName: 'actualCostHas',
          type: 'a-input',
          disabled: true,
          placeholder: ' ',
          label: '实际成本（含税）（元）',
        },
        {
          keyName: 'amountProfit',
          type: 'a-input',
          disabled: true,
          placeholder: ' ',
          label: '利润额（元）',
        },
        {
          keyName: 'profitRate',
          type: 'a-input',
          disabled: true,
          placeholder: ' ',
          label: '利润率%',
        },
        {
          keyName: 'fileInfoList',
          type: UploadList,
          span: 24,
          disabled: (!this.editable),
          label: '附件上传',
          attrs: {
            businessCode: 'FACE04',
            uploadArrys: this.form.fileInfoList,
            isShow: this.editable
          },
          fileArrysData: (e) => {
            this.$refs.customForm.validateField('fileInfoList')
          }
        },
      ]
    },
  },
  methods: {
    //选择单位
    selectOrg(val) {
      if (val && val.length) {
        this.form.branchComId = val[val.length - 2].orgId
      }
    },
    computedNum(e) {
      if (!this.form.name) {
        this.$message.warn('请先选择名称！')
        return
      }
      let authorizedAmountNo = this.form.authorizedAmountNo || 0
      let authorizedAmountTaxes = this.form.authorizedAmountTaxes || 0
      let authorizedAmountHas = MathTool.add(authorizedAmountNo, authorizedAmountTaxes)
      let actualCostHas = this.form.actualCostHas || 0
      let amountProfit = MathTool.sub(authorizedAmountHas, actualCostHas)
      this.form.authorizedAmountHas = authorizedAmountHas
      this.form.amountProfit = amountProfit
      this.form.profitRate = authorizedAmountHas > 0 ? (amountProfit / authorizedAmountHas * 100).toFixed(2) : 0
    },
    getNameList() {
      let param = {
        projectId: this.form.projectId
      }
      if (!this.form.projectId) return
        if(this.form.submissionId) {
          return new Promise((resolve, reject) => {
            let data = [{
              id: this.form.submissionId,
              name: this.form.name
            }]
            resolve({ code: 200, data })
          })
        }
        return getFilterSubmission(param).then((res) => {
          if (res.code == 0) {
            return { code: 200, data: res.data }
          }
          return { code: 200, data: [] }
        }).catch(() => {
          return { code: 200, data: [] }
        })
    },
    getDetail() {
      getFinalDetail({ id: this.$route.query.id }).then((res) => {
        if (res.code == 0) {
          console.log(res)
          const data = res.data
          this.form = data
          this.form.creatorName = this.$userInfo().name
        }
      })
    },
    save(back = true) {
      const params = { ...this.form }
      params.auditStatus = '0'
      this.defloading = true
      const api = this.type == 'add' ? finalApprovalAdd : finalApprovalUpdate
      api(params).then((res) => {
        this.defloading = false
        if (res.code == 0) {
          this.$message.success('保存草稿成功')
          if (back) {
            this.$close()
          } else {
            this.getDetail()
          }
        }
      }).catch(() => {
        this.defloading = false
      })
    },
    handleSubmit() {
      this.setProcessConfig = null;
      this.$refs.customForm.validate((valid) => {
        if (valid) {
          const params = { ...this.form }

          params.auditStatus = '1'
          const api = this.type == 'add' ? finalApprovalAdd : finalApprovalUpdate
          const msg = this.type == 'add' ? '添加' : '编辑'
          this.subloading = true
          this.submitApprovalConfirm(this.processConfig, (flag) => {
            if (!flag) {
              this.subloading = false
              return
            }
            api(params).then((res) => {
              this.subloading = false
              if (res.code == 0) {
                this.$message.success('提交成功')
                //提交时，返回id
                this.businessId = res.data?.id || this.$route.query.id;
                this.setProcessConfig = this.processConfig;
              }
            }).catch(() => {
              this.subloading = false
            })
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
</style>
